﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Xman.Extensions.Core
{
    public static class StringExtensions
    {
        /// <summary>
        /// 判断字符串是否为空
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        /// <summary>
        /// 字符串按符号分隔
        /// </summary>
        /// <param name="strs"></param>
        /// <param name="joinnode"></param>
        /// <returns></returns>
        public static List<string> ToList(this string strs, char joinnode = ',')
        {
            if (strs.IsNullOrEmpty())
            {
                return new List<string>();
            }
            var sArray = strs.Split(joinnode);
            sArray = sArray.Where(a => !a.IsNullOrEmpty()).ToArray();
            return new List<string>(sArray);
        }

        /// <summary>
        /// 字符串转为Base64编码(UTF-8)
        /// </summary>
        /// <param name="strs"></param>
        /// <returns></returns>
        public static string ToBase64Encode(this string strs)
        {
            return Convert.ToBase64String(Encoding.UTF8.GetBytes(strs));
        }

        /// <summary>
        /// 格式化json字符串
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string FormatJson(this string json)
        {
            dynamic parsedJson = JsonConvert.DeserializeObject(json);
            return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
        }

        /// <summary>
        /// 转化为32位MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMd5(this string str)
        {
            using var md5 = MD5.Create();
            var inputBytes = Encoding.UTF8.GetBytes(str);
            var hashBytes = md5.ComputeHash(inputBytes);

            var sb = new StringBuilder();
            foreach (var hashByte in hashBytes)
            {
                sb.Append(hashByte.ToString("X2"));
            }

            return sb.ToString();
        }
    }
}
